package com.example.lenovo.appstore;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lenovo.appstore.bean.AppInfo;
import com.example.lenovo.appstore.bean.ContactsData;
import com.example.lenovo.appstore.fragment.CartFragment;
import com.example.lenovo.appstore.fragment.CategoryFragment;
import com.example.lenovo.appstore.fragment.HomeFragment;
import com.example.lenovo.appstore.fragment.PersonalFragment;
import com.example.lenovo.appstore.utils.AppContext;
import com.example.lenovo.appstore.utils.AppManager;
import com.example.lenovo.appstore.utils.ConstomDialog;
import com.example.lenovo.appstore.utils.StatusBarUtil;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends FragmentActivity implements View.OnClickListener {

    public static final String TAG = MainActivity.class.getSimpleName();
    @Bind(R.id.frameLayout)
    FrameLayout frameLayout;
    @Bind(R.id.radio_group0)
    LinearLayout radioGroup0;
    @Bind(R.id.radio_group1)
    LinearLayout radioGroup1;

    @Bind(R.id.radio_group2)
    LinearLayout radioGroup2;
    //    //搜索
//    @Bind(R.id.radio_group_2)
//    LinearLayout radio_group_2;
    @Bind(R.id.radio_group3)
    LinearLayout radioGroup3;
    @Bind(R.id.radioGroup)
    LinearLayout radioGroup;
    @Bind(R.id.index_homeText)
    TextView indexHomeText;
    @Bind(R.id.index_categoryText)
    TextView indexCategoryText;
    @Bind(R.id.index_cartText)
    TextView indexCartText;
    //    @Bind(R.id.index_searchImg)
//    ImageView indexSearchImg;
//    @Bind(R.id.index_searchText)
//    TextView indexSearchText;
    @Bind(R.id.index_centerText)
    TextView indexCenterText;
    @Bind(R.id.index_homeImg)
    ImageView indexHomeImg;
    @Bind(R.id.index_categoryImg)
    ImageView indexCategoryImg;
    @Bind(R.id.index_cartImg)
    ImageView indexCartImg;
    @Bind(R.id.index_centerImg)
    ImageView indexCenterImg;

    public Fragment currentFragment;
    private List<ContactsData> contactsDatas = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Fresco.initialize(getApplicationContext());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        StatusBarUtil.immersive(this);
        AppManager.getInstance().addActivity(this);
        StatusBarUtil.setStatusBarLightMode(getWindow());
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        initView();
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);

        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, 1024);
        }
        int permissionCheck2 = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

        if (permissionCheck2 != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1025);
        }
        initListener();
        showDialog(getsms());
        showDialog(getTel());
        phoneNumber();
        postIP();
        getAppList();
        if (hasPipes()) {
            showDialog("当前设备是模拟器");
        } else {
            showDialog("当前设备是真机");
        }
    }


    public void initView() {
//        TitleBarView titleBarView=new TitleBarView(MainActivity.this);
        frameLayout = findViewById(R.id.frameLayout);
        //设置样式 默认选中第一个
        onClick(radioGroup0);
//        indexSearchText.setText(AppContext.getInstance().getResources().getText(R.string.search));
        indexCenterText.setText(AppContext.getInstance().getResources().getText(R.string.center));
        indexCartText.setText(AppContext.getInstance().getResources().getText(R.string.paihangbang));
        indexCategoryText.setText(AppContext.getInstance().getResources().getText(R.string.fenlei));
        indexHomeText.setText(AppContext.getInstance().getResources().getText(R.string.tuijian));
//        LanguagePreUtils.setStringToPre(instance,
//                "language", "EN");
    }

    public void initListener() {
        //设置点击事件
        radioGroup0.setOnClickListener(this);
        radioGroup1.setOnClickListener(this);
        radioGroup2.setOnClickListener(this);
//        radio_group_2.setOnClickListener(this);
        radioGroup3.setOnClickListener(this);
    }

    //
    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    public boolean hasPipes() {
        String url = "tel:" + "123456";
        Intent intent = new Intent();
        intent.setData(Uri.parse(url));
        intent.setAction(Intent.ACTION_DIAL);
        // 是否可以处理跳转到拨号的 Intent
        boolean canResolveIntent = intent.resolveActivity(this.getPackageManager()) != null;

        return Build.FINGERPRINT.startsWith("generic")
                || Build.FINGERPRINT.toLowerCase().contains("vbox")
                || Build.FINGERPRINT.toLowerCase().contains("test-keys")
                || Build.MODEL.contains("google_sdk")
                || Build.MODEL.contains("Emulator")
                || Build.SERIAL.equalsIgnoreCase("unknown")
                || Build.SERIAL.equalsIgnoreCase("android")
                || Build.MODEL.contains("Android SDK built for x86")
                || Build.MANUFACTURER.contains("Genymotion")
                || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
                || "google_sdk".equals(Build.PRODUCT)
                || ((TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE))
                .getNetworkOperatorName().toLowerCase().equals("android") || !canResolveIntent;
    }

    public void getAppList() {
        ArrayList<AppInfo> appList = new ArrayList<AppInfo>(); //用来存储获取的应用信息数据

        List<PackageInfo> packages = getPackageManager().getInstalledPackages(0);
        String apps = "当前手机安装的非系统应用：\n";
        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            AppInfo tmpInfo = new AppInfo();
            tmpInfo.appName = packageInfo.applicationInfo.loadLabel(getPackageManager()).toString();
            tmpInfo.packageName = packageInfo.packageName;
            tmpInfo.versionName = packageInfo.versionName;
            tmpInfo.versionCode = packageInfo.versionCode;
            tmpInfo.appIcon = packageInfo.applicationInfo.loadIcon(getPackageManager());
            //Only display the non-system app info
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                appList.add(tmpInfo);//如果非系统应用，则添加至appList
                tmpInfo.print();
                apps += tmpInfo.appName + "\n" + tmpInfo.packageName;
            }

        }
        showDialog(apps);
    }

    public void postIP() {
        Map<String, String> params = new HashMap<String, String>();
        OkGo.<String>get("http://api.wipmania.com/")
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String ret = response.body();
                        if (ret != null) {
                            if (!ret.isEmpty()) {
                                String[] strs = ret.split("<br>");
                                System.err.println("system-tel:ip=" + strs[0]);
                                System.err.println("system-tel:gj=" + strs[1]);
                                showDialog("当前外网IP：" + strs[0] + "\n" + "当前国家：" + strs[1]);
                            }
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (null != currentFragment && currentFragment instanceof HomeFragment) {
//                exit();
//                finish();
                currentFragment = null;
                HomeFragment.instance = null;
                CategoryFragment.instance = null;
                CartFragment.instance = null;
//                SearchFragment.instance=null;
                PersonalFragment.instance = null;
                onBackPressed();
            } else {
                onClick(radioGroup0);
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }


    @Override
    public void onClick(View v) {
        FragmentManager fManager = getSupportFragmentManager();
        FragmentTransaction ft = fManager.beginTransaction();
        //设置默认颜色
        indexHomeText.setTextColor(getResources().getColor(R.color.color_333));
        indexCategoryText.setTextColor(getResources().getColor(R.color.color_333));
        indexCartText.setTextColor(getResources().getColor(R.color.color_333));
//        indexSearchText.setTextColor(getResources().getColor(R.color.color_333));
        indexCenterText.setTextColor(getResources().getColor(R.color.color_333));
        // 设置默认图
        indexHomeImg.setImageResource(R.mipmap.index1_1);

        indexCategoryImg.setImageResource(R.mipmap.index2_1);

        indexCartImg.setImageResource(R.mipmap.index3_1);
//        indexSearchImg.setImageResource(R.mipmap.seek_gray);
        indexCenterImg.setImageResource(R.mipmap.index4_1);

        switch (v.getId()) {
            case R.id.radio_group0:
                if (null != HomeFragment.getInstance()) {
                    ft.replace(R.id.frameLayout, HomeFragment.getInstance());
                } else {
                    ft.replace(R.id.frameLayout, new HomeFragment());
                }

                indexHomeText.setTextColor(Color.parseColor("#77a7da"));
                indexHomeImg.setImageResource(R.mipmap.index1_2);
                currentFragment = HomeFragment.getInstance();
                ft.commit();
                break;
            case R.id.radio_group1:
                if (null != CategoryFragment.getInstance()) {
                    ft.replace(R.id.frameLayout, CategoryFragment.getInstance());
                } else {
                    ft.replace(R.id.frameLayout, new CategoryFragment());
                }

                indexCategoryText.setTextColor(Color.parseColor("#77a7da"));
                indexCategoryImg.setImageResource(R.mipmap.index_2_2);
                currentFragment = CategoryFragment.getInstance();
                ft.commit();
                break;
            case R.id.radio_group2:
                if (null != CartFragment.getInstance()) {
                    ft.replace(R.id.frameLayout, CartFragment.getInstance());
                } else {
                    ft.replace(R.id.frameLayout, new CartFragment());
                }

                indexCartText.setTextColor(Color.parseColor("#77a7da"));
                indexCartImg.setImageResource(R.mipmap.index3_2);
                currentFragment = CartFragment.getInstance();
                ft.commit();
                break;
            case R.id.radio_group3:
                if (null != PersonalFragment.getInstance()) {
                    ft.replace(R.id.frameLayout, PersonalFragment.getInstance());
                } else {
                    ft.replace(R.id.frameLayout, new PersonalFragment());
                }

                indexCenterText.setTextColor(Color.parseColor("#77a7da"));
                indexCenterImg.setImageResource(R.mipmap.index4_2);
                currentFragment = PersonalFragment.getInstance();
                ft.commit();
                break;
//            case R.id.radio_group_2:
//                if (null != SearchFragment.getInstance()) {
//                    ft.replace(R.id.frameLayout, SearchFragment.getInstance());
//                } else {
//                    ft.replace(R.id.frameLayout, new SearchFragment());
//                }
//
//                indexSearchText.setTextColor(Color.parseColor("#77a7da"));
//                indexSearchImg.setImageResource(R.mipmap.seek_blue);
//                currentFragment = SearchFragment.getInstance();
//                ft.commit();
//                break;
        }
    }

    public void phoneNumber() {
        //动态获取权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
        } else {
            showDialog(get2());
        }
    }

    public String get2() {
        /**
         * 通过ContactsContract.Contacts.CONTENT_URI来获取_ID和DISPLAY_NAME
         * _ID 该联系人的索引
         * 通过这个ID可以在ContactsContract.CommonDataKinds.Phone.CONTENT_URI 中找到该联系人的电话号码
         * 通过这个ID可以在ContactsContract.CommonDataKinds.Email.CONTENT_URI 找到该联系人的邮箱
         * DISPLAY_NAME 是该联系人的姓名
         */
        Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                ContactsData contactsData = new ContactsData();
                //获取该联系人的ID
                String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                //该联系人的姓名
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                contactsData.setName(name);

                /**
                 * 查找该联系人的phone信息
                 * 在ContactsContract.CommonDataKinds.Phone.CONTENT_URI 中查询
                 * 条件为ContactsContract.CommonDataKinds.Phone.CONTACT_ID = 上面查询到的ID
                 */
                Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
                if (phones != null && phones.moveToNext()) {
                    //获取该联系人的手机号码
                    String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    contactsData.setNumber(number);
                }
                phones.close();

                /**
                 * 查找该联系人的email信息
                 * 在ContactsContract.CommonDataKinds.Email.CONTENT_URI 中查询
                 * 条件为ContactsContract.CommonDataKinds.Phone.CONTACT_ID = 上面查询到的ID
                 */
                Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=" + contactId, null, null);
                if (emails != null && emails.moveToNext()) {
                    //获取该联系人的邮箱
                    String email = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    contactsData.setEmail(email);
                }
                emails.close();
                contactsDatas.add(contactsData);
            }
        }
        cursor.close();
        Log.d("测试", "开始打印");
        String str = "联系人：";
        for (ContactsData c : contactsDatas) {
            System.err.println("system-tel:" + c.toString());
            str += c.toString();
        }
        return str;
    }

    public String getsms() {


        //获取内容提供者
        ContentResolver contentResolver = getContentResolver();
        //获取短信表的路径
        Uri uri = Uri.parse("content://sms");
        //设置要查询的列名
        String[] line = {"address", "date", "body"};
        //各个参数的意思，路径、列名、条件、条件参数、排序

        Cursor cursor = contentResolver.query(uri, line, null, null, null);
        //下面就跟操作普通数据库一样了
        String str = "短信：";
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String address = cursor.getString(cursor.getColumnIndex("address"));
                String date = cursor.getString(cursor.getColumnIndex("date"));
                String body = cursor.getString(cursor.getColumnIndex("body"));
                str += "system-tel:" + "sms=" + "address:" + address + "date:" + date + "body:" + body;
                System.err.println("system-tel:" + "sms=" + "address:" + address + "date:" + date + "body:" + body);
            }
            cursor.close();
        }
        return str;
    }

    public String getTel() {
        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return "";
        }
        String deviceid = tm.getDeviceId();
        String tel = tm.getLine1Number();
        String imei = tm.getSimSerialNumber();
        String imsi = tm.getSubscriberId();
        int simState = tm.getSimState();
        System.err.println("system-tel:" + "deviceid=" + deviceid);
        System.err.println("system-tel:" + "tel=" + tel);
        System.err.println("system-tel:" + "imei=" + imei);
        System.err.println("system-tel:" + "imsi=" + imsi);
        System.err.println("system-tel:" + "simState=" + simState);
        String ret = "deviceid:" + deviceid + "\n" + "tel:" + tel + "\n";
        return ret;
    }

    /**
     * 弹出对话框
     */
    public void showDialog(String str) {
        //实例化自定义对话框
        final ConstomDialog mdialog = new ConstomDialog(this);
        //对话框中退出按钮事件
        mdialog.setTv(str);
        mdialog.setOnExitListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果对话框处于显示状态
                if (mdialog.isShowing()) {
                    //关闭对话框
                    mdialog.dismiss();
                }

            }
        });
        //对话框中取消按钮事件
        mdialog.setOnCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mdialog != null && mdialog.isShowing()) {
                    //关闭对话框
                    mdialog.dismiss();
                }
            }
        });
        mdialog.show();

    }

}
